'use strict';

import api from '../../utils/api';
import util from '../../utils/index';
//获取应用实例
const app = getApp()

Page({

    data:{
        productList:[],
        isNoData:false
    },

    onLoad:function () {
        this.initMyProducts();
    },
    //加载我的产品列表
    initMyProducts:function () {
      var that = this;
      let userInfo = app.globalData.userInfo;
      if (userInfo) {
        let userId = userInfo.id;
        util.request({
          url: util.templateFunc(api.userProductsUrl, { userId: userId }),
          header: {
            'content-type': 'application/json',
            'x-auth-token': wx.getStorageSync('sessionId')
          },
        }).then(res => {
          if (res && res.data.data) {
            that.setData({
              productList: res.data.data,
              isNoData: res.data.data.length === 0 ? true : false
            });
          }
        })
      }
    },

    // 产品下架
    delProduct:function (e) {
      var datas = this.data.productList;
      var that = this;
      let productId = e.currentTarget.dataset.id;
      util.request({
        url: util.templateFunc(api.offProductUrl, { id: productId }),
        header: {
          'content-type': 'application/json',
          'x-auth-token': wx.getStorageSync('sessionId')
        },
        method: 'DELETE'
      }).then(res => {
        if (res && res.errorCode === 0) {
            for(var i = 0;i< datas.length;i++ ){
                if(datas[i].id === productId){
                    datas[i].status = 1
                }
            }
            that.setData({
                productList:datas
            })

          wx.showToast({
            title: '下架成功',
            icon: 'success',
            duration: 1000
          })
        }
      })
    },


    //产品上架
    upProduct:function (e) {
        var datas = this.data.productList;
        var that = this;
        let productId = e.currentTarget.dataset.id;
        util.request({
            url: util.templateFunc(api.onShelfProductUrl, { id: productId }),
            header: {
                'content-type': 'application/json',
                'x-auth-token': wx.getStorageSync('sessionId')
            },
            method: 'PUT'
        }).then(res => {
            if (res && res.errorCode === 0) {
                for(var i = 0;i< datas.length;i++ ){
                    if(datas[i].id === productId){
                        datas[i].status = 0
                    }
                }
                that.setData({
                    productList:datas
                })

                wx.showToast({
                    title: '上架成功',
                    icon: 'success',
                    duration: 1000
                })
            }
        })
    },






    //编辑产品
    editProduct:function (e) {
        // 获取到产品id 跳转到产品编辑界面
        wx.navigateTo({
            url: '/pages/publish/publish?id='+ e.currentTarget.dataset.id
        })
    }
    
    
})